package com.bjb.vr.remote.ws.rabbitmq.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @version 1.0.0
 * @description:
 * @author: caihaibo
 * @createDate: 2022/9/7
 */
@Slf4j
public class OkHttpDownloader {

	private final String url, destFilename;

	public OkHttpDownloader(String url, String destFilename) {

		this.url = url;

		this.destFilename = destFilename;
	}

	public void download(Callback callback) {

		BufferedInputStream input = null;

		try (FileOutputStream fos = new FileOutputStream(destFilename)) {

			Request request = new Request.Builder().url(url).build();

			ResponseBody responseBody = new OkHttpClient().newCall(request).execute().body();

			long fileSize = responseBody.contentLength();

			input = new BufferedInputStream(responseBody.byteStream());

			byte[] buffer = new byte[10 * 1024 * 1024];

			int numberOfBytesRead;

			long totalNumberOfBytesRead = 0;

			while ((numberOfBytesRead = input.read(buffer)) != -1) {

				fos.write(buffer, 0, numberOfBytesRead);

				totalNumberOfBytesRead += numberOfBytesRead;

				callback.onProgress(totalNumberOfBytesRead * 100 / fileSize);

			}

			callback.onFinish();

		} catch (IOException ex) {

			callback.onError(ex);

		} finally {

			if (input != null) {

				try {

					input.close();

				} catch (IOException ex) {

					log.error(null, ex);

				}

			}

		}

	}
}
